package org.dyndns.opendemogroup.optimizer.operations;

import java.util.HashSet;

import org.dyndns.opendemogroup.optimizer.Member;

/**
 * Based on the description in Page 3 of the assignment handout.
 */
public class OrderCrossover extends OrderPreservingOperationBase
{

	/**
	 * @see OrderPreservingOperationBase#perform(Member, Member, Member, int,
	 *      int)
	 */
	@Override
	void perform ( Member parentOne, Member parentTwo, Member child, int a,
			int b )
	{
		final int length = parentOne.genome.length;
		HashSet<Double> taken = new HashSet<Double> ( );
		HashSet<Double> usedSlot = new HashSet<Double> ( );

		// { copy the items between A and B from parent 1 into the child
		for ( int i = a; i < b; i++ )
		{
			final double allele = parentOne.genome[i];
			child.genome[i] = allele;
			taken.add ( allele );
			usedSlot.add ( (double) i );
		}
		// }

		// { fill in the remaining indices with the unused items,
		// in the order that they appear in parent 2
		for ( int i = 0, j = 0; i < length; i++ )
		{
			final double allele = parentTwo.genome[i];
			if ( !taken.contains ( allele ) )
			{
				// { find the next unused slot "j"
				while ( usedSlot.contains ( (double) j ) )
				{
					j++;
				}
				// }
				child.genome[j] = allele;
				usedSlot.add ( (double) j );
			}
		}
		// }
	}

}
